import { SCALAR as g, isScalar as S } from '../nodes/identity.js';
import { Scalar as m } from '../nodes/Scalar.js';
import { resolveBlockScalar as A } from './resolve-block-scalar.js';
import { resolveFlowScalar as d } from './resolve-flow-scalar.js';
function R(s, a, r, i) {
  const {
      value: c,
      type: f,
      comment: e,
      range: o,
    } = a.type === 'block-scalar'
      ? A(a, s.options.strict, i)
      : d(a, s.options.strict, i),
    t = r
      ? s.directives.tagName(r.source, l => i(r, 'TAG_RESOLVE_FAILED', l))
      : null,
    u =
      r && t
        ? L(s.schema, c, t, r, i)
        : a.type === 'scalar'
          ? E(s, c, a, i)
          : s.schema[g];
  let n;
  try {
    const l = u.resolve(c, p => i(r ?? a, 'TAG_RESOLVE_FAILED', p), s.options);
    n = S(l) ? l : new m(l);
  } catch (l) {
    const p = l instanceof Error ? l.message : String(l);
    i(r ?? a, 'TAG_RESOLVE_FAILED', p), (n = new m(c));
  }
  return (
    (n.range = o),
    (n.source = c),
    f && (n.type = f),
    t && (n.tag = t),
    u.format && (n.format = u.format),
    e && (n.comment = e),
    n
  );
}
function L(s, a, r, i, c) {
  var o;
  if (r === '!') return s[g];
  const f = [];
  for (const t of s.tags)
    if (!t.collection && t.tag === r)
      if (t.default && t.test) f.push(t);
      else return t;
  for (const t of f) if ((o = t.test) != null && o.test(a)) return t;
  const e = s.knownTags[r];
  return e && !e.collection
    ? (s.tags.push(Object.assign({}, e, { default: !1, test: void 0 })), e)
    : (c(
        i,
        'TAG_RESOLVE_FAILED',
        `Unresolved tag: ${r}`,
        r !== 'tag:yaml.org,2002:str',
      ),
      s[g]);
}
function E({ directives: s, schema: a }, r, i, c) {
  const f =
    a.tags.find(e => {
      var o;
      return e.default && ((o = e.test) == null ? void 0 : o.test(r));
    }) || a[g];
  if (a.compat) {
    const e =
      a.compat.find(o => {
        var t;
        return o.default && ((t = o.test) == null ? void 0 : t.test(r));
      }) ?? a[g];
    if (f.tag !== e.tag) {
      const o = s.tagString(f.tag),
        t = s.tagString(e.tag),
        u = `Value may be parsed as either ${o} or ${t}`;
      c(i, 'TAG_RESOLVE_FAILED', u, !0);
    }
  }
  return f;
}
export { R as composeScalar };
